﻿using System;
using System.Timers;
using System.Windows.Forms;

namespace Test_Automation
{
    public partial class Form_Main : Form
    {
        public Form_Main()
        {
            InitializeComponent();
            CheckForIllegalCrossThreadCalls = false;
        }
        private HslCommunication.ModBus.ModbusTcpNet PLC;
        bool plc_connected = false;
        System.Timers.Timer timer_get_current_position;

        void plc_connect() {
            PLC = new HslCommunication.ModBus.ModbusTcpNet(config_json.PLC_IP);   // 站号1
            PLC.AddressStartWithZero = true;
            PLC.DataFormat = HslCommunication.Core.DataFormat.CDAB;

            HslCommunication.OperateResult resut = PLC.ConnectServer();
            if (resut.IsSuccess)
            {
                tb_memo.Text += "PLC连接成功！";
                plc_connected = true;
            }
            else
            {
                tb_memo.Text += "PLC连接失败！";
                ts1.Text = "连接PLC失败！";
            }
        }
        private static readonly log4net.ILog logger = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
        private void addmemo_txt(string memo)
        {
            memo = DateTime.Now.ToString("[yyyy-M-d HH:mm:ss.fff] ") + memo + "\r\n";
            tb_memo.AppendText(memo);
            tb_memo.ScrollToCaret();
            logger.Info(memo);
        }
        private void Form_Main_Load(object sender, EventArgs e)
        {
            SOFT_VER.Text = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString();
            config_json.config_json_readall();
            tb_zeroX.Text = config_json.X轴原点位置v;
            tb_zeroY.Text = config_json.Y轴原点位置v;
            tb_zeroZ.Text = config_json.Z轴原点位置v;

            serialPort_VG876.PortName = config_json.VG870_PortName;
           
            test_timeout_timer = new System.Timers.Timer(10000);
            test_timeout_timer.Elapsed += new System.Timers.ElapsedEventHandler(test_timeout_timer_Tick);
            test_timeout_timer.AutoReset = false;
            test_timeout_timer.Enabled = false;
            ResultReadTimer = new System.Timers.Timer(1000);  //每秒刷新测试时间
            ResultReadTimer.Elapsed += new System.Timers.ElapsedEventHandler(ResultReadTimer_Tick);//到时间的时候执行事件；
            ResultReadTimer.AutoReset = false;//设置是执行一次（false）还是一直执行(true)；
            ResultReadTimer.Enabled = false;

            timer_get_current_position = new System.Timers.Timer(1000);
            timer_get_current_position.Elapsed += new System.Timers.ElapsedEventHandler(timer_get_current_position_Tick);
            timer_get_current_position.AutoReset = false;
            timer_get_current_position.Enabled = false;

            serialPort_VG876.PortName = config_json.VG870_PortName;
            conn =
           new MySql.Data.MySqlClient.MySqlConnection(
               "Database=" + config_json.mysql_database_name + ";" +
               "Data Source=" + config_json.Mysql_IP + ";User Id=" + config_json.Mysql_User + ";Password=" + config_json.Mysql_Pass + ";charset=utf8;");
           // 加载产商和型号();
        }
        public static MySql.Data.MySqlClient.MySqlConnection conn;
        private void 加载产商和型号()
        {
            conn.Open();
            MySql.Data.MySqlClient.MySqlCommand cmd = new MySql.Data.MySqlClient.MySqlCommand("select distinct 生产厂商 from  产品参数", conn);
            MySql.Data.MySqlClient.MySqlDataReader dr = cmd.ExecuteReader();
            while  (dr.Read())
            {
                cbb生产厂商.Items.Add( dr[0].ToString());
            }
            dr.Close();
            conn.Close();
            if (cbb生产厂商.Items.Count>0)  cbb生产厂商.SelectedIndex = 0;
            
        }

        private void timer_get_current_position_Tick(object sender, ElapsedEventArgs e)
        {
            if (plc_connected)
            {
                tb_nowX.Text = PLC.ReadInt32(config_json.X轴当前位置a).Content.ToString();
                tb_nowY.Text = PLC.ReadInt32(config_json.Y轴当前位置a).Content.ToString();
                tb_nowZ.Text = PLC.ReadInt32(config_json.Z轴当前位置a).Content.ToString();
                timer_get_current_position.Enabled = true;
            }
        }

        private void 退出ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void 亮度计ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Form_CA410 f = new Form_CA410();
            f.ShowDialog();
        }

        private void 机械系统ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Form_control f = new Form_control();
            f.ShowDialog();

        }

        private void btn_white_pattern_Click(object sender, EventArgs e)
        {
            if (serialPort_VG876.IsOpen == false) serialPort_VG876.Open();
            try { serialPort_VG876.Write(config_json.pattern_white, 0, config_json.pattern_white.Length); } catch { }
        }

        //检测头复位
        private void button3_Click(object sender, EventArgs e)
        {
            if (plc_connected == false) plc_connect();
            if (plc_connected == false) return;
            PLC.Write(config_json.X轴复位位置a, Convert.ToInt32(tb_zeroX.Text));
            PLC.Write(config_json.Y轴复位位置a, Convert.ToInt32(tb_zeroY.Text));
            PLC.Write(config_json.Z轴复位位置a, Convert.ToInt32(tb_zeroZ.Text));
            PLC.Write(config_json.复位写入, 1);
        }

        private void button4_Click_1(object sender, EventArgs e)
        {
            Form_160 f = new Form_160();
            f.ShowDialog();
        }

        private void button5_Click(object sender, EventArgs e)
        {
            Form_control f = new Form_control();
            f.ShowDialog();
        }

        System.Timers.Timer ResultReadTimer;
        System.Timers.Timer test_timeout_timer; 
        private void btn_cs200read_Click(object sender, EventArgs e)
        {
            cs200.RunCS200();
            try
            { //清空result.txt文件内容
                System.IO.StreamWriter sw = new System.IO.StreamWriter("result.txt");
                sw.Write("");
                sw.Close();

                System.IO.StreamWriter sw2 = new System.IO.StreamWriter("input.txt");
                sw2.Write("zyb");
                sw2.Close();
            }
            catch (Exception er)
            {
                MessageBox.Show(er.Message);
                return;
            }
            test_timeout_timer.Enabled = true;
            ResultReadTimer.Enabled = true;
        }

        private void test_timeout_timer_Tick(object sender, ElapsedEventArgs e)
        {
            label20.Text = "超时";
        }

        private void ResultReadTimer_Tick(object sender, ElapsedEventArgs e)
        {
            string result = ReadResult("result.txt"); //OK00,0,2,1, 1,0,    0,0,20,      6.313,     0.3102,     0.3489
            if (result == "")
            {
                ResultReadTimer.Enabled = true;
                return;
            }
            string[] data = result.Replace(" ","").Split(',');
            if (data.Length>9) tb_light_value.Text = data[9];
            test_timeout_timer.Enabled = false;
        }
        public string ReadResult(string file)
        {
            string str = "";
            //判断文件是否存在
            if (!System.IO.File.Exists(file))  //文件不存在
            {
                return "";
            }
            else
            {
                try
                {
                    //文件已存在
                    //读取文件
                    System.IO.StreamReader sr = new System.IO.StreamReader(file);
                    str = sr.ReadToEnd();
                    sr.Close();
                    System.Threading.Thread.Sleep(100);
                    //清空result.txt文件内容
                    System.IO.StreamWriter sw = new System.IO.StreamWriter(file);
                    sw.Write("");
                    sw.Close();
                }
                catch (Exception ex)
                {
                    
                }
            }
            return str.Trim();
        }

        private void Form_Main_FormClosing(object sender, FormClosingEventArgs e)
        {
            cs200.ExitCS200();
        }

        private void 信号发生器ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Form_VG876 f = new Form_VG876();
            f.ShowDialog();
        }

        private void btn_movetocenter_Click(object sender, EventArgs e)
        {
            if (plc_connected == false) plc_connect();
            if (plc_connected == false) return;
            PLC.Write(config_json.X轴复位位置a,Convert.ToInt32( tb_centerX.Text));
            PLC.Write(config_json.Y轴复位位置a, Convert.ToInt32(tb_centerY.Text));
            PLC.Write(config_json.Z轴复位位置a, Convert.ToInt32(tb_centerZ.Text));
            PLC.Write(config_json.复位写入, 1);
        }

        private void btn_zero_save_Click(object sender, EventArgs e)
        {
            config_json.save("X轴原点位置v", tb_zeroX.Text);
            config_json.save("Y轴原点位置v", tb_zeroY.Text);
            config_json.save("Z轴原点位置v", tb_zeroZ.Text);
            MessageBox.Show("保存成功");
        }

        private void button6_Click(object sender, EventArgs e)
        {
            conn.Open();
            //检查厂商型号是否已存在
            MySql.Data.MySqlClient.MySqlCommand cmd = 
                new MySql.Data.MySqlClient.MySqlCommand("select id from  产品参数 where 生产厂商='" + cbb生产厂商.Text + "' and 产品型号='"+cbb产品型号.Text+"'", conn);
            MySql.Data.MySqlClient.MySqlDataReader dr = cmd.ExecuteReader();
            if (dr.Read()) //已存在则更新
            {
                dr.Close();
                MySql.Data.MySqlClient.MySqlCommand cmd2 =
               new MySql.Data.MySqlClient.MySqlCommand("update  产品参数 set 中心坐标='" + tb_centerX.Text + "," + tb_centerY.Text + "," + tb_centerZ.Text + "' where 生产厂商='" + cbb生产厂商.Text + "' and 产品型号='" + cbb产品型号.Text + "'", conn);
                cmd2.ExecuteNonQuery();
            }
            else // 不存在则添加
            {
                dr.Close();
                MySql.Data.MySqlClient.MySqlCommand cmd3 =
                  new MySql.Data.MySqlClient.MySqlCommand("insert into  产品参数 (生产厂商,产品型号,中心坐标) values('"+cbb生产厂商.Text+"','"+cbb产品型号.Text+"','"+ tb_centerX.Text + "','" + tb_centerY.Text + "','" + tb_centerZ.Text + "')", conn);
                cmd3.ExecuteNonQuery();

            }
            conn.Close();

            config_json.save("X轴中心位置v", tb_centerX.Text);
            config_json.save("Y轴中心位置v", tb_centerY.Text);
            config_json.save("Z轴中心位置v", tb_centerZ.Text);
            MessageBox.Show("保存成功");
        }
        float test_a=0, test_b=0;
        private void btn_get_Click(object sender, EventArgs e)
        {
            cs200.RunCS200();
            try
            { //清空result.txt文件内容
                System.IO.StreamWriter sw = new System.IO.StreamWriter("result.txt");
                sw.Write("");
                sw.Close();

                System.IO.StreamWriter sw2 = new System.IO.StreamWriter("input.txt");
                sw2.Write("mes");
                sw2.Close();
            }
            catch (Exception er)
            {
                MessageBox.Show(er.Message);
                return;
            }
            test_timeout_timer.Enabled = true;
            ResultReadTimer.Enabled = true;
        }

        private void serialPort_VG876_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
        {
            System.Threading.Thread.Sleep(100);

            int n = serialPort_VG876.BytesToRead;
            byte[] buf = new byte[n];
            serialPort_VG876.Read(buf, 0, n);
            tb_memo.Text+="VG876收到的数据:" + byteToHexStr(buf);
        }
        public static string byteToHexStr(byte[] bytes)
        {
            string returnStr = "";
            if (bytes != null)
            {
                for (int i = 0; i < bytes.Length; i++)
                {
                    returnStr += bytes[i].ToString("X2") + " ";
                }
            }
            return returnStr;
        }

        private void btn_get_current_position_Click(object sender, EventArgs e)
        {
            if (plc_connected)
            {
                tb_nowX.Text = PLC.ReadInt32(config_json.X轴当前位置a).Content.ToString();
                tb_nowY.Text = PLC.ReadInt32(config_json.Y轴当前位置a).Content.ToString();
                tb_nowZ.Text = PLC.ReadInt32(config_json.Z轴当前位置a).Content.ToString();
                tb_memo.Text += "X轴当前位置:" + tb_nowX.Text + "\r\n";
                tb_memo.Text += "Y轴当前位置:" + tb_nowY.Text + "\r\n";
                tb_memo.Text += "Z轴当前位置:" + tb_nowZ.Text + "\r\n";
                timer_get_current_position.Enabled = true;
            }
        }

        private void btn_move_x_Click(object sender, EventArgs e)
        {
            if (plc_connected)
            {
                HslCommunication.OperateResult opresult = PLC.Write(config_json.X轴相对运动坐标写入a, Convert.ToInt32(tb_x.Text));
                HslCommunication.OperateResult opresult2 = PLC.Write(config_json.X轴相对运动启动a, 1);
                tb_memo.Text += config_json.X轴相对运动坐标写入a + "写入：" + tb_x.Text + "\r\n";
            }
        }

        private void btn_move_y_Click(object sender, EventArgs e)
        {
            if (plc_connected)
            {
                HslCommunication.OperateResult opresult = PLC.Write(config_json.Y轴相对运动坐标写入a, Convert.ToInt32(tb_y.Text));
                HslCommunication.OperateResult opresult2 = PLC.Write(config_json.Y轴相对运动启动a, 1);
                tb_memo.Text += config_json.Y轴相对运动坐标写入a + "写入：" + tb_y.Text + "\r\n";
            }
        }

        private void btn_move_z_Click(object sender, EventArgs e)
        {
            if (plc_connected)
            {
                HslCommunication.OperateResult opresult = PLC.Write(config_json.Z轴相对运动坐标写入a, Convert.ToInt32(tb_z.Text));
                HslCommunication.OperateResult opresult2 = PLC.Write(config_json.Z轴相对运动启动a, 1);
                tb_memo.Text += config_json.Z轴相对运动坐标写入a + "写入：" + tb_z.Text + "\r\n";
            }
        }

        private void btn_move_r_Click(object sender, EventArgs e)
        {
            if (plc_connected)
            {
                HslCommunication.OperateResult opresult = PLC.Write(config_json.R轴相对运动坐标写入a, Convert.ToInt32(tb_r.Text));
                HslCommunication.OperateResult opresult2 = PLC.Write(config_json.R轴相对运动启动a, 1);
                tb_memo.Text += config_json.R轴相对运动坐标写入a + "写入：" + tb_r.Text + "\r\n";
            }
        }

        private void btn_plc_disconnect_Click(object sender, EventArgs e)
        {
            PLC.ConnectClose();
            plc_connected = false;
        }

        private void btn_plc_connect_Click(object sender, EventArgs e)
        {
            plc_connect();
            if (plc_connected)
            {
                tb_nowX.Text = PLC.ReadInt32(config_json.X轴当前位置a).Content.ToString();
                tb_nowY.Text = PLC.ReadInt32(config_json.Y轴当前位置a).Content.ToString();
                tb_nowZ.Text = PLC.ReadInt32(config_json.Z轴当前位置a).Content.ToString();
                tb_memo.Text += "X轴当前位置:" + tb_nowX.Text + "\r\n";
                tb_memo.Text += "Y轴当前位置:" + tb_nowY.Text + "\r\n";
                tb_memo.Text += "Z轴当前位置:" + tb_nowZ.Text + "\r\n";
                timer_get_current_position.Enabled = true;
            }
        }
        private void cbb生产厂商_SelectedIndexChanged(object sender, EventArgs e)
        {
            cbb产品型号.Items.Clear();
           conn.Open();
            MySql.Data.MySqlClient.MySqlCommand cmd = new MySql.Data.MySqlClient.MySqlCommand("select distinct 产品型号 from  产品参数 where 生产厂商='"+cbb生产厂商.Text+ "' order by 产品型号", conn);
            MySql.Data.MySqlClient.MySqlDataReader dr = cmd.ExecuteReader();
            while (dr.Read())
            {
               cbb产品型号.Items.Add(dr[0].ToString());
            }
            conn.Close();
            if (cbb产品型号.Items.Count > 0) cbb产品型号.SelectedIndex = 0;
          
        }

        private void cbb产品型号_SelectedIndexChanged(object sender, EventArgs e)
        {
            conn.Open();
            MySql.Data.MySqlClient.MySqlCommand cmd = new MySql.Data.MySqlClient.MySqlCommand("select distinct 中心坐标 from  产品参数 where 产品型号='" + cbb产品型号.Text + "'", conn);
            MySql.Data.MySqlClient.MySqlDataReader dr = cmd.ExecuteReader();
            if (dr.Read())
            {
                try
                {
                    string[] str = dr[0].ToString().Split(',');
                    tb_centerX.Text = str[0];
                    tb_centerY.Text = str[1];
                    tb_centerZ.Text = str[2];
                }
                catch {
                }
            }
            conn.Close();
        }

        private void button7_Click(object sender, EventArgs e)
        {
            Form_Gamma f = new Form_Gamma();
            f.ShowDialog();
        }

        private void button1_Click_1(object sender, EventArgs e)
        {
            Form_Gamma_CA410_Autoreset f = new Form_Gamma_CA410_Autoreset();
            f.ShowDialog();
        }

        private void button2_Click(object sender, EventArgs e)
        {
            Form_Gamma_CA410_SDK2net f = new Form_Gamma_CA410_SDK2net();
            f.ShowDialog();
        }

        private void button5_Click_1(object sender, EventArgs e)
        {
            conn.Open();
            //检查厂商型号是否已存在
            MySql.Data.MySqlClient.MySqlCommand cmd =
                new MySql.Data.MySqlClient.MySqlCommand("select id from  测试数据 where 测试编号='" + tb_test_proj.Text + "'", conn);
            MySql.Data.MySqlClient.MySqlDataReader dr = cmd.ExecuteReader();
            if (dr.Read()) //已存在则更新
            {
                dr.Close();
                MySql.Data.MySqlClient.MySqlCommand cmd2 =
               new MySql.Data.MySqlClient.MySqlCommand("update  测试数据 set 最大亮度='" + tb_light_value.Text + "' where 测试编号='" + tb_test_proj.Text + "'", conn);
                cmd2.ExecuteNonQuery();
            }
            else // 不存在则添加
            {
                dr.Close();
                MySql.Data.MySqlClient.MySqlCommand cmd3 =
                  new MySql.Data.MySqlClient.MySqlCommand("insert into  测试数据 (测试编号,最大亮度,测试时间) values('" + tb_test_proj.Text + "','" + tb_light_value.Text + "','" + tb_centerX.Text + "',now())", conn);
                cmd3.ExecuteNonQuery();

            }
            conn.Close();
        }
    }
    }
